// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#pragma once

#include <pollux/dwio/common/file_sink.h>

namespace kumo::pollux::text {
    /// Takes character(s) and writes into a 'sink'.
    /// It buffers the characters(s) in memory before flushing to the sink.
    /// The upper limit character count is specified by 'flushBufferSize'.
    class BufferedWriterSink {
    public:
        BufferedWriterSink(
            std::unique_ptr<dwio::common::FileSink> sink,
            std::shared_ptr<memory::MemoryPool> pool,
            uint64_t flushBufferSize);

        ~BufferedWriterSink();

        void write(char value);

        void write(const char *data, uint64_t size);

        void flush();

        /// Discard the data in buffer and close the buffer and fileSink.
        void abort();

        /// Flush the data in buffer to fileSink and close the buffer and fileSink.
        void close();

    private:
        void reserveBuffer();

        const std::unique_ptr<dwio::common::FileSink> sink_;
        const std::shared_ptr<memory::MemoryPool> pool_;
        // The buffer size limit and triggers flush if exceeds this limit.
        const uint64_t flushBufferSize_;
        const std::unique_ptr<dwio::common::DataBuffer<char> > buf_;
        // TODO: add a flag to indicate sink is aborted to prevent flush and write
        // operations after aborted
    };
} // namespace kumo::pollux::text
